/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */
package com.inspur.edp.jittojava.temp;

import com.inspur.edp.jittojava.context.entity.MavenDependency;
import com.inspur.edp.jittojava.core.GenerateServiceCore;
import com.inspur.edp.jittojava.spi.AfterGeneratorAction;
import com.inspur.edp.lcm.metadata.common.FileServiceImp;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.ArrayList;

/**
 * @Classname AfterGenerator
 * @Description TODO
 * @Date 2019/12/17 16:02
 * @Created by liu_bintr
 * @Version 1.0
 */
public class AfterGenerator implements AfterGeneratorAction {

    GenerateServiceCore generateService = new GenerateServiceCore();
    Utils utils = new Utils();

    @Override
    public void afterGenerator(String projPath) {
        addProjectDependency(projPath, null, utils.getDefaultDependency());
        FileServiceImp fileService = new FileServiceImp();
        String runtimePath = Paths.get(projPath).resolve("java/code/runtime").toString();
        if (fileService.isDirectoryExist(runtimePath)) {
            try {
                fileService.deleteAllFilesUnderDirectory(runtimePath);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
            generateService.removeRuntimeModule(projPath);
        }
        generateService.modifyPom(projPath, utils.getExtendDependency());
        generateService.modifyPom(projPath, utils.getSgfExtendDependency());
    }

    public void addProjectDependency(String projectPath, String currentJarPath,
        ArrayList<MavenDependency> dependencyArrayList) {
        String javaPath = getJavaProjPath(projectPath);
        // 安装jar包到maven仓库
        Utils.installPackage(javaPath, currentJarPath, dependencyArrayList);
        // 修改pom文件
        generateService.modifyPom(projectPath, dependencyArrayList);
    }

    private String getJavaProjPath(String projPath) {
        String javaPath = Paths.get(projPath).resolve("java").toString();
        String javaProjPath = Paths.get(javaPath).resolve(com.inspur.edp.lcm.metadata.common.Utils.getMavenProName()).toString();

        return javaProjPath;
    }
}
